<?php

namespace App\Models\System;

use App\Common\Exception\ErrorException;
use App\Models\Information\TeacherBase;
use App\Models\Teachers;
use App\Services\System\ClassroomService;
use App\Services\System\GradeService;
use App\Services\System\StudentService;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Support\Facades\DB;
use App\Services\System\GroupService;
use Illuminate\Support\Facades\Log;


class User extends Authenticatable
{
    protected $table = 'users';
    protected $guarded = [];

    const ACTIVE_FLAG_FORBIDDEN = 0;
    const ACTIVE_FLAG_ACTIVE    = 1;
    const ACTIVE_FLAG_PENDING   = 2;

    private static $active_flags = [
        self::ACTIVE_FLAG_FORBIDDEN => '禁用',
        self::ACTIVE_FLAG_ACTIVE    => '正常',
        self::ACTIVE_FLAG_PENDING   => '未通过验证',
    ];

    const ADMIN_FLAG_SHARE  = -1;
    const ADMIN_FLAG_NONE   = 0;
    const ADMIN_FLAG_GROUP  = 1;
    const ADMIN_FLAG_SUPER  = 2;

    private static $admin_flags = [
        self::ADMIN_FLAG_SHARE => '公共帐号',
        self::ADMIN_FLAG_NONE  => '普通用户',
        self::ADMIN_FLAG_GROUP => '组管理员',
        self::ADMIN_FLAG_SUPER => '系统管理员',
    ];


    public function getCurRoleIdAttribute()
    {
        $roleIds = $this->roles()->pluck('roles.id')->toArray();
        if ($this->attributes['curr_role_id']){
            return in_array($this->attributes['curr_role_id'], $roleIds)?
                $this->attributes['curr_role_id'] : $roleIds[0];
        }else{
            $this->curr_role_id = $roleIds[0];
            $this->save();
            return $this->curr_role_id;
        }
    }

    //获取当前角色类别
    public function getCurRoleTypeAttribute()
    {
        if ($this->attributes['curr_role_id']){
            $roleId = $this->attributes['curr_role_id'];
            $role = Role::where('id', $roleId)->first();
        }else{
            $role = $this->roles()->first();
        }

        return $role->role_type;
    }

    public function getIsCheckerAttribute()
    {
        $isChecker = false;

        if ($this->attributes['curr_role_id']){
            $roleId = $this->attributes['curr_role_id'];
        }else{
            $role = $this->roles()->first();
            $roleId = $role->id ?? '';
        }

        if(in_array($roleId, [SYSTEM_ROLE, ADMIN_ROLE])) {
            $isChecker = true;
        }

        return $isChecker;
    }

    /**
     * 用户拥有的角色
     */
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

    /**
     * 当前用户是否有任一角色slug
     *
     * @param array|string $role_slugs 角色slug字符串或数组（多个角色）
     * @param boolean      $only       是否判断有且仅有某一角色，没有其它角色
     * @return bool
     */
    public function hasRole($role_slugs, $only = false): bool
    {
        if (!is_array($role_slugs)) $role_slugs = [$role_slugs];
        foreach ($role_slugs as $role_slug) {
            if ($role_slug == $this->cur_role_id) {
                if ($only) { //有且仅有某一角色
                    return count($this->roles) == 1;
                } else { //只要拥有某一角色
                    return true;
                }
            }
        }
        return false;
    }

    public function currentRole()
    {
        return $this->belongsTo(Role::class, 'curr_role_id', 'id');
    }

    public function group()
    {
        return $this->belongsTo(Group::class, 'group_id', 'group_id');
    }

    //用户老师关联信息
     public function teacher()
     {
         return $this->hasOne(Teachers::class, 'eduid', 'eduid');
     }

    //用户老师基础关联信息
    // public function base()
    // {
    //     return $this->hasOne(TeacherBase::class, 'user_id', 'user_id');
    // }

    //老师带班信息
    // public function class()
    // {
    //     return $this->hasOne(ClassTeacher::class, 'teacher_id', 'user_id')->with('classroom');
    // }

    public function roleId()
    {
        return $this->curr_role_id > 0 ? $this->curr_role_id : $this->roles()->first()->id;
    }

    public static function lastgroup($groupId)
    {
        $lastGroup = null;
        $group_id = $groupId;
        $group_flag = -1;
        while (!in_array($group_flag, [0, 1])){
            $group = Group::where('group_id', $group_id)->first();
            if (!$group)break;

            $group_flag = $group['group_flag'];
            $parent_id = $group['parent_id'];

            if(in_array($group_flag, [0, 1]) || $parent_id == 0){
                $lastGroup = $group;
                break;
            }else{
                $group_id = $group['parent_id'];
            }
        }

        return $lastGroup;
    }

    /**
     * 获取与用户关联的学校
     */
    public function school()
    {
        $school = null;
        $group_id = $this->group_id;
        /** @var GroupService $groupService */
        $groupService = app('groupService');
        $group_flag = 0;
        while ($group_flag != 1){
            $filters = [['id', '=', $group_id]];
            $group = $groupService->getCore($filters,FALSE);

            $group_flag = $group['group_flag'];
            $parent_id = $group['parent_id'];
            if($group_flag == 1 || $parent_id == 0){
                $school = $group;
                break;
            }else{
                $group_id = $group['parent_id'];
            }
        }

        return $school;
    }

    /**
     * 获取与用户关联的学校组id
     */
    public function schoolid()
    {
        $school = $this->school();

        return $school['id'];
    }

    //获取用户权限操作
    public function getUserOper($roleid=0)
    {
        $user = auth()->user();
        $role_id = $user->cur_role_id;

        $powers = DB::table('rolepowers')->where('role_id','=',$role_id)->pluck('actionid')->toArray();

        return $powers;
    }



    /**
     * 保存来自中心 UAC 的用户数据
     *
     * @param array $data 来自中心 UAC 的用户数据数组
     */
    public static function saveUserFromCenter($data)
    {
        $fields = ['user_id', 'group_id', 'user_name', 'nickname', 'birthday', 'gender', 'email', 'create_date', 'active_flag', 'admin_flag', 'user_type', 'id_card', 'is_del'];
        $update_data = [];
        foreach ($fields as $field) {
            if (isset($data[$field])) {
                if ($field == 'create_date' && !$data[$field]) {
                    $data[$field] = date('Y-m-d H:i:s');
                }
                if($field == 'birthday'){
                    if(!empty($data[$field])){
                        $update_data[$field] = $data[$field];
                    }
                }if($field == 'create_date'){
                    if($data[$field] !== '0000-00-00 00:00:00'){
                        $update_data[$field] = $data[$field];
                    }
                }else{
                    $update_data[$field] = $data[$field];
                }
            }
        }

        $user = self::updateOrCreate(
            ['user_uuid' => $data['user_uuid']],
            $update_data
        );


        // 节点版最上层组的组管理员在节点版是学校管理员（类似中心版的超级管理员）
        if (isset($update_data['group_id']) && isset($update_data['admin_flag']) && ($update_data['admin_flag'] == self::ADMIN_FLAG_SUPER || $update_data['admin_flag'] == self::ADMIN_FLAG_GROUP)) {
            $user->roles()->detach();
            $user->roles()->attach(SYSTEM_ROLE);
            //            $group = Group::find($update_data['group_id']);
            //            if ($group && $group->parent_id == 0) {
            //                $update_data['admin_flag'] = self::ADMIN_FLAG_SUPER;
            //            }
        }else{
            $user->roles()->detach();
            $user->roles()->attach(PTJS_ROLE);
            // if (isset($update_data['user_type']) && ($update_data['user_type'][2] == '1')) {
            //     $user->roles()->attach(TEACHER_ROLEID);
            // }

            // if (isset($update_data['user_type']) && ($update_data['user_type'][3] == '1')) {
            //     $user->roles()->attach(STUDENT_ROLEID);
            // }
        }
    }

    /**
     * 保存来自中心 UAC 的用户数据(rpc)
     *
     * @param array $data 来自中心 UAC 的用户数据数组
     */
    public static function saveUserFromCenter_rpc($data)
    {
        $fields = ['group_id', 'user_name', 'nickname', 'birthday', 'gender', 'email', 'create_date', 'active_flag', 'admin_flag', 'user_type', 'id_card', 'is_del', 'eduid'];
        $update_data = [];
        foreach ($fields as $field) {
            if (isset($data[$field])) {

                if($field == 'group_id'){
                    $update_data['group_id'] = $data[$field];
                }
                if($field == 'user_name'){
                    $update_data['username'] = $data['user_id'];
                    $update_data['nickname'] = $data[$field];
                }
                if($field == 'email'){
                    $update_data['email'] = $data[$field];
                }
                if($field == 'is_del'){
                    $update_data['deleted'] = $data[$field];
                }
                $update_data['eduid'] = $data['eduid'] ?? '';
                $update_data['user_type'] = $data['user_type'] ?? '';
            }
        }

        $user = self::updateOrCreate(
            ['user_id' => $data['user_id']],
            $update_data
        );

        $user->roles()->detach();
        if (isset($update_data['group_id']) && isset($update_data['admin_flag']) && ($update_data['admin_flag'] == self::ADMIN_FLAG_SUPER || $update_data['admin_flag'] == self::ADMIN_FLAG_GROUP)) {
            $user->roles()->attach(SYSTEM_ROLE);
        }else{
            $user->roles()->attach(PTJS_ROLE);
        }

    }
}
